package com.heima.filter;

import com.heima.properties.AuthProperties;
import com.heima.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;

import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class PrintAnyGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求url
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getPath().toString();
        //不是直接放行
        if (isExclude(uri)){
            log.info("放行的uri：{}",uri);
            return chain.filter(exchange);
        }
        // 3.是：获取请求头，鉴权
        //log.info("要鉴权的url:{}", url);
        // 3.1 获取请求头
        String token = request.getHeaders().getFirst("authorization");
        // 3.2 鉴权
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
            String userInfo = userId.toString();
            // 3.3 token合法，获取userId，传递到下一个微服务
            exchange.mutate()
                    //增加一个请求头
                    .request(b -> b.header("user-info", userInfo))
                    .build();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            // 3.4 token非法，返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    private boolean isExclude(String uri) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath,uri)){
                return true;
            }
        }
        return false;
    }


    @Override
    public int getOrder() {
        // 过滤器执行顺序，值越小，优先级越高
        return 0;
    }
}